package lc_2875_无限数组的最短子数组;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class Solution {

    public int minSizeSubarray(int[] nums, int target) {
        long ans = Integer.MAX_VALUE;
        long sum = Arrays.stream(nums).mapToLong(e -> 1l * e).sum();
        int size = nums.length;
        Map<Long, Integer> s = new HashMap<>();
        long tot = 0;
        for (int i = size - 1; i >= 0; i--) {
            tot += nums[i];
            s.put(tot, i);
        }
        Map<Long, Integer> p = new HashMap<>();
        p.put(0L, -1);
        tot = 0;
        for (int i = 0; i < size; i++) {
            tot += nums[i];
            long pp = ((tot - target) % sum + sum) % sum;
            if (p.containsKey(pp)) {
                long a = i - p.get(pp) + size * (target - tot + pp) / sum;
                ans = Math.min(ans, a);
            }
            long ps = ((target - tot) % sum + sum) % sum;
            if (s.containsKey(ps)) {
                long a = size - s.get(ps) + i + 1 + size * (target - tot - ps) / sum;
                ans = Math.min(ans, a);
            }
            p.put(tot, i);
        }
        return ans == Integer.MAX_VALUE ? -1 : (int) ans;
    }
}